import 'package:dio/dio.dart';

abstract class CostomInterceptorWrapper {
  Dio dio;
  Interceptor interceptor;

  Interceptor createDefault();
  void responseInterceptor(
      Response response, ResponseInterceptorHandler handler);
  void errorInterceptor(DioException error, ErrorInterceptorHandler handler);
  void requestInterceptor(
      RequestOptions options, RequestInterceptorHandler handler);
}

class CostomInterceptor extends CostomInterceptorWrapper {
  Dio dio;
  Interceptor interceptor;
  String d;

  CostomInterceptor(this.dio, {Interceptor interceptor}) {
    print('---------- interceptor ----------');
    interceptor = interceptor ?? createDefault();
    dio.interceptors.add(interceptor);
  }

  Interceptor createDefault() {
    return InterceptorsWrapper(
      onRequest: requestInterceptor,
      onError: errorInterceptor,
      onResponse: responseInterceptor,
    );
  }

  @override
  void errorInterceptor(DioException error, ErrorInterceptorHandler handler) {
    print('errorInterceptor');
    handler.next(error);
  }

  @override
  void responseInterceptor(
      Response response, ResponseInterceptorHandler handler) {
    print('responseInterceptor');
    handler.next(response);
  }

  @override
  void requestInterceptor(
      RequestOptions options, RequestInterceptorHandler handler) {
    print('requestInterceptor');
    handler.next(options);
  }
}

class HttpCore {
  Dio dio;

  HttpCore(this.dio);

  static Dio getInstance({BaseOptions options, Interceptor interceptor}) {
    CostomInterceptor custom = CostomInterceptor(Dio(options ?? null));
    if (interceptor != null) {
      custom.dio.interceptors.add(interceptor);
    }
    return custom.dio;
  }

  addInterceptors(InterceptorsWrapper interceptor) {
    dio.interceptors.add(interceptor);
  }

  removeInterceptors(InterceptorsWrapper interceptor) {
    dio.interceptors.remove(interceptor);
  }
}

CostomInterceptor custom = CostomInterceptor(Dio(BaseOptions()));

// http://send.wxbus163.cn/weather/getCityList
class HttpUtils {
  static get(String url) {
    return custom.dio.get(url);
  }

  static post(String url, {dynamic data}) {
    // return Dio().post(url, data: data);
    return custom.dio.post(url, data: data);
  }

  static download(String url, dynamic savePath, onReceiveProgress) {
    return custom.dio.download(
      url,
      savePath,
      onReceiveProgress: onReceiveProgress,
    );
  }
}
